<?php
class ModelStockLend extends Model {

	public function getotalend($data = array()){

		$sql = "SELECT COUNT(DISTINCT lo.loan_order_id) AS count FROM `".DB_PREFIX."loan_order` lo LEFT JOIN `".DB_PREFIX."loan_order_details` lod ON lod.loan_order_id = lo.loan_order_id LEFT JOIN `".DB_PREFIX."loan_status` ls ON ls.id = lo.status LEFT JOIN `".DB_PREFIX."warehouse` w ON w.warehouse_id = lo.from_warehouse_id";

		if(!empty($data['filter_lend_id'])){
			$where[] = "lo.loan_order_id = '".$data['filter_lend_id']."'";
		}

		if(!empty($data['filter_name_code'])){
			$where[] = "lod.product_code like '%".$data['filter_name_code']."%'";
		}

		if($data['filter_status'] != 'empty' && $data['filter_status'] != null){
			$where[] = "ls.id = '".$data['filter_status']."'";
		}

		if($data['filter_warehouse'] != 'empty' && $data['filter_status'] != null){
			$where[] = "w.warehouse_id = '".$data['filter_warehouse']."'";
		}

		if(!empty($data['filter_add_date_start'])){
			$where[] = "lo.date_added > '".$data['filter_add_date_start']."'";
		}

		if(!empty($data['filter_add_date_end'])){
			$where[] = "lo.date_added < '".$data['filter_add_date_end']."'";
		}

		if(!empty($where))
			$sql .= ' WHERE '.implode(' AND ',$where);

		$query_count = $this->db->query($sql);

		return $query_count->row['count'];

	 }

	public function getlends($data = array()){
		$sql = "SELECT lo.loan_order_id,lo.shipping_name,u.username,w.name AS fwarehouse,l.logcenter_name,lo.shipping_tel,lo.shipping_address,lo.status, lo.date_added,lo.date_modified AS status_id,ls.status_name AS status,lo.user_id FROM `".DB_PREFIX."loan_order` lo LEFT JOIN `".DB_PREFIX."loan_status` ls ON ls.id = lo.status LEFT JOIN `".DB_PREFIX."warehouse` w ON w.warehouse_id = lo.from_warehouse_id LEFT JOIN `".DB_PREFIX."logcenters` l ON l.logcenter_id = lo.logcenter_id LEFT JOIN `".DB_PREFIX."user` u ON u.user_id = lo.user_id";

		if(!empty($data['filter_lend_id'])){
			$where[] = "lo.loan_order_id = '".$data['filter_lend_id']."'";
		}

		if(!empty($data['filter_name_code'])){
			$where[] = "lo.loan_order_id IN (SELECT loan_order_id FROM `".DB_PREFIX."loan_order_details` WHERE product_code like '%".$data['filter_name_code']."%')";
		}

		if($data['filter_status'] != 'empty' && $data['filter_status'] != null){
			$where[] = "lo.status = '".$data['filter_status']."'";
		}

		if($data['filter_warehouse'] != 'empty' && $data['filter_status'] != null){
			$where[] = "lo.from_warehouse_id = '".$data['filter_warehouse']."'";
		}

		if(!empty($data['filter_add_date_start'])){
			$where[] = "lo.date_added > '".$data['filter_add_date_start']."'";
		}

		if(!empty($data['filter_add_date_end'])){
			$where[] = "lo.date_added < '".$data['filter_add_date_end']."'";
		}

		if(!empty($where))
			$sql .= ' WHERE '.implode(' AND ',$where);

		$sort_data = array(
			'lo.loan_order_id',
			'lo.status'
		);

		if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
			$sql .= " ORDER BY " . $data['sort'];
		} else {
			$sql .= " ORDER BY lo.loan_order_id";
		}

		if (isset($data['order']) && ($data['order'] == 'DESC')) {
			$sql .= " DESC";
		} else {
			$sql .= " ASC";
		}

		if (isset($data['start']) || isset($data['limit'])) {
			if ($data['start'] < 0) {
				$data['start'] = 0;
			}

			if ($data['limit'] < 1) {
				$data['limit'] = 20;
			}

			$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
		}
		//return $sql;
		$query = $this->db->query($sql);

		$result = $query->rows;

		foreach($result as $key=>$val){

			$approvel_ids_arr = explode(',',trim($val['approvel_ids'],','));

			$approvel = array();

			foreach($approvel_ids_arr as $val2){

				$sql = "SELECT username FROM `".DB_PREFIX."user` WHERE user_id = '".$val2."'";

				$username_query = $this->db->query($sql);

				$approvel[] = $username_query->row['username'];

			}

			$approvel = implode(',',$approvel);

			$result[$key]['approvel'] = $approvel;

		}

		return $result;

	}

	public function getlend($loan_order_id){

		$sql = "SELECT lo.loan_order_id,lo.comment,lo.shipping_name,lo.shipping_tel,lo.shipping_address,lo.comment,lo.date_added,lo.date_modified,lo.from_warehouse_id,lo.status AS status_id,ls.status_name AS status,w.name AS fwarehouse,l.logcenter_name AS logcenter,u.username,lo.user_id AS louserid,ll.user_id AS lluserid FROM `".DB_PREFIX."loan_order` lo LEFT JOIN `".DB_PREFIX."loan_status` ls ON ls.id = lo.status LEFT JOIN `".DB_PREFIX."warehouse` w ON w.warehouse_id = lo.from_warehouse_id LEFT JOIN `".DB_PREFIX."logcenters` l ON l.logcenter_id = lo.logcenter_id LEFT JOIN `".DB_PREFIX."user` u ON u.user_id = lo.user_id LEFT JOIN `".DB_PREFIX."logcenters` ll ON ll.logcenter_id = lo.from_warehouse_id WHERE loan_order_id = '".$loan_order_id."'";
//return $sql;
		$query = $this->db->query($sql);

		$result = $query->row;

		foreach($result as $key=>$val){

			if($key == 'approvel_ids'){

				$approvel_ids_arr = explode(',',trim($val,','));

				$approvel = array();

				foreach($approvel_ids_arr as $val2){

					$sql = "SELECT username FROM `".DB_PREFIX."user` WHERE user_id = '".$val2."'";

					$username_query = $this->db->query($sql);

					$approvel[] = $username_query->row['username'];

				}

				$approvel = implode(',',$approvel);

				$result['approvel'] = $approvel;

			}

			if($key == 'approveled_ids'){

				$approveled_ids_arr = explode(',',trim($val,','));

				$approveled = array();

				foreach($approveled_ids_arr as $val2){

					$sql = "SELECT username FROM `".DB_PREFIX."user` WHERE user_id = '".$val2."'";

					$username_query = $this->db->query($sql);

					$approveled[] = $username_query->row['username'];

				}

				$approveled = implode(',',$approveled);

				$result['approveled'] = $approveled;

			}

		}

		return $result;

	}

	public function getUsers(){

		$sql = "SELECT user_id,username,fullname FROM `" . DB_PREFIX . "user`";

		$sql .= " ORDER BY username";

		$sql .= " ASC";

		$query = $this->db->query($sql);

		return $query->rows;

	}

	public function getuserbyloanid($loan_order_id){

		$sql = "SELECT approvel_ids FROM `".DB_PREFIX."loan_order` WHERE loan_order_id = '".$loan_order_id."'";

		$query = $this->db->query($sql);

		$approvel_ids = trim($query->row['approvel_ids'],',');

		$sql = "SELECT user_id,username,fullname FROM `".DB_PREFIX."user` WHERE user_id IN (".$approvel_ids.")";

		$user_query = $this->db->query($sql);

		return $user_query->rows;

	}

	public function getWarehouse(){

		$sql = "SELECT warehouse_id,name FROM `".DB_PREFIX."warehouse` WHERE type < 3 AND status = 1";

		$query = $this->db->query($sql);

		return $query->rows;

	}

	public function getlogcenters(){

		$sql = "SELECT * FROM `".DB_PREFIX."logcenters`";

		$query = $this->db->query($sql);

		return $query->rows;

	}

	public function getlogcenterid($loan_order_id){

		$sql = "SELECT logcenter_id FROM `".DB_PREFIX."loan_order` WHERE loan_order_id = '".$loan_order_id."'";

		$query = $this->db->query($sql);

		return $query->row['logcenter_id'];

	}

	public function getLogcenter($logcenter_id){

		$sql = "SELECT * FROM `".DB_PREFIX."logcenters` WHERE logcenter_id = '".$logcenter_id."'";

		$query = $this->db->query($sql);

		return $query->row;

	}

	public function getloandetail($loan_order_id){

		$sql = "SELECT lod.*,lod.product_code AS code,lod.apply_qty AS num,pd.name,p.sku FROM `".DB_PREFIX."loan_order_details` lod LEFT JOIN `".DB_PREFIX."product_option_value` pov ON pov.product_code = lod.product_code LEFT JOIN `".DB_PREFIX."product_description` pd ON pd.product_id = pov.product_id LEFT JOIN `".DB_PREFIX."product` p ON p.product_id = pov.product_id WHERE loan_order_id = '".$loan_order_id."'";

		$query = $this->db->query($sql);

		return $query->rows;

	}

	public function addlend($data){

		$sql = "INSERT INTO `".DB_PREFIX."loan_order`";

		if(!empty($this->user->getId())){
			$set[] = "user_id = '".$this->user->getId()."'";
		}

		// if(!empty($data['approvel'])){
		// 	$set[] = "approvel = '".$data['approvel']."'";
		// }

		if(!empty($data['logcenter_id'])){
			$set[] = "logcenter_id = '".$data['logcenter_id']."'";
		}

		if(!empty($data['shipping_name'])){
			$set[] = "shipping_name = '".$data['shipping_name']."'";
		}

		if(!empty($data['shipping_tel'])){
			$set[] = "shipping_tel = '".$data['shipping_tel']."'";
		}

		if(!empty($data['shipping_address'])){
			$set[] = "shipping_address = '".$data['shipping_address']."'";
		}

		if(!empty($data['from_warehouse_id'])){
			$set[] = "from_warehouse_id = '".$data['from_warehouse_id']."'";
		}

		if(!empty($data['comment'])){
			$set[] = "comment = '".$data['comment']."'";
		}

		$set[] = "status = 0";
		$set[] = "date_added = NOW()";

		$sql .= ' SET '.implode(',',$set);

		$this->db->query($sql);

		$loan_order_id = $this->db->getLastId();

		return $loan_order_id;

	}

	public function addlendetail($data,$loan_order_id,$from_warehouse){

		$new_product_arr = array();

		foreach($data as $val){

			if(array_key_exists($val['code'],$new_product_arr)){

				$new_product_arr[$val['code']] += $val['num'];

			}else{

				$new_product_arr[$val['code']] = $val['num'];

			}

		}

		foreach($new_product_arr as $key=>$val){

			$sql = "SELECT product_id FROM `".DB_PREFIX."product_option_value` WHERE product_code = '".$key."'";

			$query = $this->db->query($sql);

			$pid = $query->row['product_id'];

			$sql = "SELECT IF((SELECT price FROM `".DB_PREFIX."product_special` ps WHERE ps.product_id = p.product_id AND ((ps.date_start <= CURRENT_DATE() AND ps.date_end >= CURRENT_DATE()) OR (ps.date_start = '0000-00-00' AND ps.date_end = '0000-00-00')) GROUP BY ps.priority HAVING ps.priority = MIN(ps.priority)),(SELECT price FROM `".DB_PREFIX."product_special` ps WHERE ps.product_id = p.product_id AND ((ps.date_start <= CURRENT_DATE() AND ps.date_end >= CURRENT_DATE()) OR (ps.date_start = '0000-00-00' AND ps.date_end = '0000-00-00')) GROUP BY ps.priority HAVING ps.priority = MIN(ps.priority)),p.price) AS price FROM `".DB_PREFIX."product` p WHERE p.product_id = '".$pid."'";

			$query = $this->db->query($sql);

			$price = $query->row['price'];

			$sql = "SELECT product_cost FROM `".DB_PREFIX."vendor` WHERE vproduct_id = '".$pid."'";

			$query = $this->db->query($sql);

			$cost = $query->row['product_cost'];

			$sql = "INSERT INTO `".DB_PREFIX."loan_order_details` SET loan_order_id = '".$loan_order_id."',product_code = '".$key."',product_price = '".floatval($price)."',product_cost = '".floatval($cost)."',apply_qty = '".intval($val)."',return_qty_bad='".intval($val)."'";
			 $this->db->query($sql);

		}

	}

	public function get_status(){

		$sql = "SELECT id,status_name FROM `".DB_PREFIX."loan_status`";

		$query = $this->db->query($sql);

		return $query->rows;

	}

	public function get_warehouse(){

		$sql = "SELECT warehouse_id,name FROM `".DB_PREFIX."warehouse` WHERE type < 3 AND status = 1";

		$query = $this->db->query($sql);

		return $query->rows;

	}

	public function get_allwarehouse(){

		$sql = "SELECT warehouse_id,name FROM `".DB_PREFIX."warehouse` WHERE status = 1";

		$query = $this->db->query($sql);

		return $query->rows;

	}

	public function getlendetail($loan_order_id){

		$sql = "SELECT lod.*,pd.name AS product_name,p.sku AS product_sku FROM `".DB_PREFIX."loan_order_details` lod LEFT JOIN `".DB_PREFIX."product_option_value` pov ON pov.product_code = lod.product_code LEFT JOIN `".DB_PREFIX."product_description` pd ON pd.product_id = pov.product_id LEFT JOIN `".DB_PREFIX."product` p ON p.product_id = pov.product_id WHERE lod.loan_order_id = '".$loan_order_id."'";

		$query = $this->db->query($sql);

		return $query->rows;

	}

	public function gethistory($loan_order_id){

		// $sql = "SELECT u.username,lsb.status_name AS lsbs_name,lsa.status_name AS lsas_name,loh.comment,loh.date_added FROM `".DB_PREFIX."loan_order_history` loh LEFT JOIN `".DB_PREFIX."user` u ON u.user_id = loh.user_id LEFT JOIN `".DB_PREFIX."loan_status` lsb ON lsb.id = loh.status_before LEFT JOIN `".DB_PREFIX."loan_status` lsa ON lsa.id = loh.status_after WHERE loan_order_id = '".$loan_order_id."' ORDER BY loh.loan_order_history_id DESC";

		 $sql = "SELECT u.username,loh.status_before AS lsbs_name,loh.status_after AS lsas_name,loh.comment,loh.date_added FROM `".DB_PREFIX."loan_order_history` loh LEFT JOIN `".DB_PREFIX."user` u ON u.user_id = loh.user_id LEFT JOIN `".DB_PREFIX."loan_status` lsb ON lsb.id = loh.status_before WHERE loan_order_id = '".$loan_order_id."'ORDER BY loh.loan_order_history_id DESC";
		$query = $this->db->query($sql);

		return $query->rows;

	}

	public function getstockoutbyreferid($loan_order_id){
		$sql = "SELECT so.*,rt.name AS rtname,wh.name AS whname,u.username,ts.name AS tsname FROM `".DB_PREFIX."stock_out` so LEFT JOIN `".DB_PREFIX."refer_type` rt ON so.refer_type_id = rt.refer_type_id LEFT JOIN `".DB_PREFIX."warehouse` wh ON so.warehouse_id = wh.warehouse_id LEFT JOIN `".DB_PREFIX."user` u ON so.user_id = u.user_id LEFT JOIN `".DB_PREFIX."inout_state` ts ON so.status = ts.id";

		if($loan_order_id){
			$sql .= " WHERE refer_id = '".$loan_order_id."' AND so.refer_type_id = 6";

			$query = $this->db->query($sql);
			// echo $sql;

			return $query->rows;
		}else
			return null;
	}

	public function plusnub($data){
									$sql="SELECT return_qty_good,apply_qty,loan_order_details_id  FROM `".DB_PREFIX."loan_order_details` WHERE product_code= ".$data['product_code']. " AND loan_order_id='".$data['id']."' AND return_qty_bad>0";
	          			$query = $this->db->query($sql);
	          			$row[]=$query->row;
								 	foreach ($row as $k => $v){
											if(empty($v)){
												 return "false";
											}else{
													//return $v['apply_qty'];
															$examine=$this->db->query("SELECT available_quantity,id FROM ".DB_PREFIX." inventory WHERE warehouse_id='".(int)$data['warehouse_id']. "'AND product_code='".$data['product_code']."'");
															if($examine->num_rows!==0){
																	$check[]=$examine->rows;
																	foreach ($check as $ke => $va) {
																							foreach ($va as $key => $value) {
																							  //加库存修改日志
																							  				$nb=$value['available_quantity'];
																												$numb=(int)$nb+(int)$data['nub'];
																												$inventoryHistoryData = array(
																						            'inventory_id'  => $value['id'],//inventory表PK
																						            'product_code'  => $data['product_code'],//商品编码（冗余字段）
																						            'warehouse_id'  => $data['warehouse_id'],//仓库编号（冗余字段）
																						            'account_qty'   => (int)$numb,//财务数量变更（正+ 负-）
																						            'available_qty' => (int)$numb,//可用数量变更（正+ 负-）
																						            'comment'       => '还货单：'.$data['id'].'归还'.$data['nub'].'件编号为：'.$data['product_code'].'的商品',//备注（入库单完成、损益单完成、出库单生成、出库单修改、出库单作废）
																						            'user_id'       => $this->user->getId(),//操作人PK
																						            'date_added'    => date('Y-m-d H:i:s'),//条目创建时间
																						            );
																						            $success=M('inventory_history')->data($inventoryHistoryData)->add();
																						            $returnqty=$v['apply_qty']-$v['return_qty_good']-$data['nub'];
																						            $loanorderhistory = array(
																						            'loan_order_id'=>$data['id'],
																						            'user_id'  => $this->user->getId(),
																						            'status_before'  =>$v['apply_qty']-$v['return_qty_good'],
																						            'status_after' => $returnqty,
																						            'comment'       => '还货单：'.$data['id'].'归还'.$data['nub'].'件编号为：'.$data['product_code'].'的商品',
																						            'date_added'    => date('Y-m-d H:i:s'),//条目创建时间

																						            );
																						            $succ=M('loan_order_history')->data($loanorderhistory)->add();
																							          if($success&&$succ){
																													  $s=$this->db->query("UPDATE " . DB_PREFIX . "inventory SET available_quantity = '" . $numb. "',date_modified='".date('Y-m-d H:i:s')."' WHERE warehouse_id= '" . (int)$data['warehouse_id']. "' AND product_code='".$data['product_code']."'");
															 									          		$goodnb=$v['return_qty_good'];
																								          		$returngood=$goodnb+$data['nub'];

																								          		$return_qty_good=$this->db->query("UPDATE " . DB_PREFIX . "loan_order_details SET return_qty_good = '".$returngood."',return_qty_bad='".$returnqty."' WHERE  loan_order_id='" .$data['id']. "' AND product_code='".$data['product_code']."'");
																								          			if($returnqty==0){

																																$sq=$this->db->query("SELECT return_qty_good,apply_qty FROM `".DB_PREFIX."loan_order_details` WHERE product_code= ".$data['product_code']."' AND return_qty_bad>0");
																																						$ro[]=$sq->row;
																																						 	foreach ($ro as $kk => $vv){
																																									if(empty($vv)){
																																											$orderstatus=$this->db->query("UPDATE " . DB_PREFIX . "loan_order SET status = 6,date_modified='".date('Y-m-d H:i:s')."' WHERE  loan_order_id='" .$data['id']. "'");
																																										}
																								          										}
																								          				}

																								          			//借货入库
																																$stockin = M('stock_in');
																														  	$datan = array('refer_id'=>$data['id'],
																														  		'refer_type_id'=> 7,
																														  		'warehouse_id'=>(int)$data['warehouse_id'],
																														  		'user_id'=>1,
																														  		'buy_money'=>0,
																														  		'status'=>2,
																														  		'comment'=>"还货单",
																														  		'date_added'=>date('Y-m-d H:i:s'),
																														  		'in_date'=>date('Y-m-d H:i:s'));
																														  		$stockid = $stockin->data($datan)->add();

																														  		$stockind = M('stock_in_detail');
																															  	$datad = array('in_id'=>$stockid,
																															  		'product_code'=>$data['product_code'],
																															  		 'product_quantity'=>$data['nub'],
																															  		 'product_price'=>0,
																															  		 'products_money'=>0,
																																	'date_added'=>date('Y-m-d H:i:s'));
																															  	$stock=$stockind->data($datad)->add();

																								          				$this->load->model('stock/stock_in');
																								          				$comments = "增加还货入库单" ;
      																														$this->model_stock_stock_in->addStHistory($stock, $this->user->getId(),$comments);
																							          			if($s&&$return_qty_good){
																							          					return $stockid;
																							          			}else{
																							          					return 11;
																							          			}
																								        }else{
																								        		return 22;
																								        }
																									}
																			}
															}else{
																									$returnqty=$v['apply_qty']-$v['return_qty_good']-$data['nub'];
																			            $loanorderhistory = array(
																			            'loan_order_id'=>$data['id'],
																			            'user_id'  => $this->user->getId(),
																			            'status_before'  =>$v['apply_qty']-$v['return_qty_good'],
																			            'status_after' => $returnqty,
																			            'comment'       => '还货单：'.$data['id'].'归还'.$data['nub'].'件编号为：'.$data['product_code'].'的商品',
																			            'date_added'    => date('Y-m-d H:i:s'),//条目创建时间

																			            );
																			            $succ=M('loan_order_history')->data($loanorderhistory)->add();
																								if($succ){
																												$da = array(
																													'warehouse_id'=>$data['warehouse_id'],
																									  			'product_code'=>$data['product_code'],
																									  		 	'available_quantity'=>(int)$data['nub'],
																									  		 	'account_quantity'=>(int)$data['nub'],
																													'date_added'=>date('Y-m-d H:i:s'));
																													$inventoryPK = M('inventory')->data($da)->add();
																													$inventoryHistoryData = array(
																							            'inventory_id'  => $inventoryPK,//inventory表PK
																							            'product_code'  => $data['product_code'],//商品编码（冗余字段）
																							            'warehouse_id'  => $data['warehouse_id'],//仓库编号（冗余字段）
																							            'account_qty'   => (int)$data['nub'],//财务数量变更（正+ 负-）
																							            'available_qty' => (int)$data['nub'],//可用数量变更（正+ 负-）
																							            'comment'       => '还货单：'.$data['id'].'归还'.$data['nub'].'件编号为：'.$data['product_code'].'的商品',//备注（入库单完成、损益单完成、出库单生成、出库单修改、出库单作废）
																							            'user_id'       => $this->user->getId(),//操作人PK
																							            'date_added'    => date('Y-m-d H:i:s'),//条目创建时间
																							            );
																							            $success=M('inventory_history')->data($inventoryHistoryData)->add();
																								          if($success){
																									            $goodnb=$v['return_qty_good'];
																													    $returngood=$goodnb+$data['nub'];
																													    $return_qty_good=$this->db->query("UPDATE " . DB_PREFIX . "loan_order_details SET return_qty_good = '".$returngood."' ,return_qty_bad='".$returnqty."'WHERE  loan_order_id='" .$data['id']. "' AND product_code='".$data['product_code']."'");
																													    	if($returnqty==0){

																																$sq=$this->db->query("SELECT return_qty_good,apply_qty FROM `".DB_PREFIX."loan_order_details` WHERE product_code= ".$data['product_code']."' AND return_qty_bad>0");
																																						$ro[]=$sq->row;
																																						 	foreach ($ro as $kk => $vv){
																																									if(empty($vv)){
																																											$orderstatus=$this->db->query("UPDATE " . DB_PREFIX . "loan_order SET status = 6,date_modified='".date('Y-m-d H:i:s')."' WHERE  loan_order_id='" .$data['id']. "'");
																																										}
																								          										}
																								          				}
																												          			//借货入库
																																				$stockin = M('stock_in');
																																		  	$datan = array('refer_id'=>$data['id'],
																																		  		'refer_type_id'=> 7,
																																		  		'warehouse_id'=>(int)$data['warehouse_id'],
																																		  		'user_id'=>1,
																																		  		'buy_money'=>0,
																																		  		'status'=>2,
																																		  		'comment'=>"还货单",
																																		  		'date_added'=>date('Y-m-d H:i:s'),
																																		  		'in_date'=>date('Y-m-d H:i:s'));
																																		  		$stockid = $stockin->data($datan)->add();

																																		  		$stockind = M('stock_in_detail');
																																			  	$datad = array('in_id'=>$stockid,
																																			  		'product_code'=>$data['product_code'],
																																			  		 'product_quantity'=>$data['nub'],
																																			  		 'product_price'=>0,
																																			  		 'products_money'=>0,
																																					'date_added'=>date('Y-m-d H:i:s'));
																																			  	$stock=$stockind->data($datad)->add();

																												          				$this->load->model('stock/stock_in');
																												          				$comments = "增加还货入库单" ;
				      																														$this->model_stock_stock_in->addStHistory($stock, $this->user->getId(),$comments);
																																    if($return_qty_good&&$orderstatus){
																																    	     return  true;
																																    }else{
																																    	return 11;
																																    }
																													}
																					        }else{
																					                           return 22;
																					        }
																		}

											}
								}

			}

	public function del_loan_order($loan_order_id){
			$loanorderhistory = array(
							  'loan_order_id'=>$loan_order_id,
								'user_id'  => $this->user->getId(),
								'status_before'  =>0,
								'status_after' => 0,
								'comment'       => '删除'.$loan_order_id,
								'date_added'    => date('Y-m-d H:i:s'),);
			$succ=M('loan_order_history')->data($loanorderhistory)->add();
			if($succ){
				$loan_order = M('loan_order')->where(array('loan_order_id'=>$loan_order_id))->delete();
				$loan_order_details=M('loan_order_details')->where(array('loan_order_id'=>$loan_order_id))->delete();
				if($loan_order&&$loan_order_details){
					return true;
				}else{
					return false;
				}
			}else{
				return false;
			}


	}


}
